package nl.rainbowsheep.reisorg.cust.site.service;

import java.util.ArrayList;
import java.util.List;
import nl.rainbowsheep.reisorg.cust.site.authentication.BasicAuthInterceptor;
import nl.rainbowsheep.reisorg.cust.site.viewmodel.TripViewmodel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class TripService {

    @Value("${api.url}")
    String url;

    public TripViewmodel[] getAll() {
        RestTemplate template = new RestTemplate();
        final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new BasicAuthInterceptor());
        template.setInterceptors(interceptors);
        TripViewmodel[] trips = template.getForObject(url + "/trip/getall?predefined=true" + "&" + getLocaleParam(), TripViewmodel[].class);
        return trips;
    }

    public TripViewmodel getById(long id) {
        RestTemplate template = new RestTemplate();
        final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new BasicAuthInterceptor());
        template.setInterceptors(interceptors);
        TripViewmodel trip = template.getForObject(url + "/trip/gettrip?id=" + id + "&" + getLocaleParam(), TripViewmodel.class);
        return trip;
    }

    public TripViewmodel[] getSearchResult(int persons, List<String> countryNames) {

        RestTemplate template = new RestTemplate();
        final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new BasicAuthInterceptor());
        template.setInterceptors(interceptors);

        //starts with ?<paramname>=<paramvalue>&<paramname>=<paramvalue>..and so on
        StringBuilder searchParams = new StringBuilder();
        searchParams.append("?");

        if (!countryNames.isEmpty()) {
            for (String countryName : countryNames) {
                searchParams.append("country=").append(countryName).append("&");
            }
        }
        searchParams.append("persons=").append(persons).append("&");
        searchParams.append(getLocaleParam()).append("&");
        searchParams.deleteCharAt(searchParams.length() - 1);
        TripViewmodel[] trips = template.getForObject(url + "/trip/searchresult" + searchParams, TripViewmodel[].class);
        return trips;
    }

    /**
     * Get current locale (from cookie)
     *
     * @return string with locale param
     */
    private String getLocaleParam() {
        return "locale=" + LocaleContextHolder.getLocale().getLanguage();
    }
}
